<?php
namespace app\index\controller;

use think\Controller;
use think\View;

class Address extends CheckMember
{
    /**
     * 收货地址 首页
     * @return View
     */
    public function index() {
        $data = $this->local_invoke_api('get_address_list', ['member_id' => session('member_id')]);
        $this->assign('data', $data['data']);

        $request = input('param.request', '');
        $url = $request == 'order' ? $_SERVER['HTTP_REFERER'] : '';
        session('back_order_url', $url);
        return view();
    }

    /**
     * 新增收获地址
     * @return View
     */
    public function save_address() {
        $id = input('param.id', 0);
        if (request()->isAjax()) {
            $param = input('param.');
            $param['member_id'] = session('member_id');
            $data = $this->local_invoke_api('save_address', $param);
            return json($data);
        } else {
            $data = ['data' => []];
            if ($id > 0) {
                $data = $this->local_invoke_api('get_address_info', ['id' => $id, 'member_id' => session('member_id')]);
            }
            $this->assign('data', $data['data']);
            return view();
        }
    }

    /**
     * 设置默认地址
     * @return \think\response\Json
     */
    public function set_default()
    {
        $id = input('param.id', 0);
        $data = \app\api\service\Address::save_default_address(['id' => $id, 'member_id' => session('member_id')]);
        return json($data);
    }

    /**
     * 删除收货地址
     * @return \think\response\Json
     */
    public function remove_address()
    {
        $id = input('param.id', 0);
        $data = \app\api\service\Address::delete_address(['id' => $id, 'member_id' => session('member_id')]);
        return json($data);
    }
}
